package com.PlantVsZombies.ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import com.PlantVsZombies.Bullet.SunCollection;
import com.PlantVsZombies.Plants.Sun;
import com.PlantVsZombies.Zombies.Pass;
import com.PlantVsZombies.common.Life;
import com.PlantVsZombies.common.Plant;
import com.PlantVsZombies.constant.Constant;
import com.PlantVsZombies.constant.GameVariable;
import com.PlantVsZombies.constant.PlantType;
import com.PlantVsZombies.game.MainFrame;
import com.PlantVsZombies.game.Menu;
import com.PlantVsZombies.online.ServerThread;
import com.PlantVsZombies.util.ImageUtil;
import com.PlantVsZombies.util.MP3Player;
import com.PlantVsZombies.util.MusicPlay;
import com.PlantVsZombies.util.MusicUtil;

/**
 * 
 * 游戏主界面
 * 
 * 
 * @author Administrator
 *
 */
public class GamePanel extends JPanel implements Constant, MouseListener, MouseMotionListener {

	PlantsBar plantsbar; // 植物框
	PlantsMap plantsmap; // 游戏场地

	PlantType choosingPlant = PlantType.NONE; // 鼠标选择的植物类型
	Plant tempPlant = null; // 植物阴影

	int mouseX; // 鼠标移动坐标
	int mouseY;

	int shadowX; // 植物阴影坐标
	int shadowY;
	int backgroudX; // 背景起始坐标
	Image backimage = ImageUtil.BACKGROUND2; // 背景图片
	int beginIndex; // 画倒计时
	/** 是否画背景 */
	boolean backflag = true;
	boolean isPaintBegin = false;
	boolean start = false; // 游戏开始标志
	MP3Player backmusic2;
	MusicPlay backmusic1;
	MusicPlay passmusic = new MusicPlay(MusicUtil.PASS);
	Pass pass;

	public int choosPass = 1;
	public static Thread t;
	public static String gamestate = "start";
	public static boolean isGameOver;
	public static boolean isPass;
	public boolean isSelect = false;

	/**
	 * 总控制器 用于菜单点击触发
	 */
	public void Action() {
		
		Init();
		backmusic1 = new MusicPlay(MusicUtil.backmusic1);
		backmusic1.play();
		// 添加鼠标监听
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
		// 添加键盘监听
		this.addKeyListener(new myKeyListener());
	}

	public void Init() {
		backmusic2 = new MP3Player(MusicUtil.backmusic3);
		start = false;
		gamestate = "start";
		isGameOver = false;
		isPass = false;
		backgroudX = -1; // 背景起始坐标
		beginIndex = 500; // 画倒计时
		backflag = true;
		isPaintBegin = false;
		plantsbar = new PlantsBar();
		plantsmap = new PlantsMap();
		pass = new Pass(choosPass);
		pass.setLive(true);
		t = new Thread(new mainThread());
		Thread serverThread = null;
		if (GameVariable.PORT != null) {
			// 端口号不为空 则是联机对战
			serverThread = new Thread(new ServerThread(plantsmap, GameVariable.PORT, t));
			serverThread.start();
		} else {
			t.start();
		}
		backmusic2 = new MP3Player(MusicUtil.backmusic4);

	}

	// 游戏启动器
	public void startAction() {
		if (!plantsbar.isAlive()) {
			plantsbar.start();
			System.out.println("开始");
			pass.start();
		}
		if (!plantsmap.isAlive()) {
			backgroudX = -150;
			plantsmap.start();
		}
		if (!backmusic2.isAlive()) {
			backmusic2.start();
		}
	}

	// 游戏结束
	public void gameOver() {
		// gamestate = "gameover";
		isGameOver = true;
		backmusic1.stop();
		backmusic2.Stop();
		new MusicPlay(MusicUtil.END).play();
		plantsbar.setSuspend(true);
		plantsmap.setSuspend(true);
		pass.setSuspend(true);
		pass.setLive(false);
		plantsmap.isLive = false;
		plantsbar.isLive = false;
	}

	// 游戏暂停
	public void pauseGame() {
		gamestate = "pause";

		this.plantsbar.setSuspend(true);
		this.plantsmap.setSuspend(true);
		this.pass.setSuspend(true);
		for (int i = 0; i < plantsmap.getZombies().size(); i++) {
			plantsmap.getZombies().get(i).setSuspend(true);
		}
		for (int i = 0; i < plantsmap.getPlants().size(); i++) {
			for (int j = 0; j < plantsmap.getPlants().get(i).getBullet().size(); j++) {
				plantsmap.getPlants().get(i).getBullet().get(j).setSuspend(true);
			}
			plantsmap.getPlants().get(i).setSuspend(true);
		}
		for (int i = 0; i < plantsmap.getSun().size(); i++) {
			plantsmap.getSun().get(i).setSuspend(true);
		}
		for (int i = 0; i < plantsmap.getBomb().size(); i++) {
			plantsmap.getBomb().get(i).setSuspend(true);
		}
	}

	// 游戏继续
	public void continueGame() {
		gamestate = "start";

		plantsbar.setSuspend(false);
		plantsmap.setSuspend(false);
		pass.setSuspend(false);
		for (int i = 0; i < plantsmap.getZombies().size(); i++) {
			plantsmap.getZombies().get(i).setSuspend(false);
		}
		for (int i = 0; i < plantsmap.getPlants().size(); i++) {
			for (int j = 0; j < plantsmap.getPlants().get(i).getBullet().size(); j++) {
				plantsmap.getPlants().get(i).getBullet().get(j).setSuspend(false);
			}
			plantsmap.getPlants().get(i).setSuspend(false);
		}
		for (int i = 0; i < plantsmap.getSun().size(); i++) {
			plantsmap.getSun().get(i).setSuspend(false);
		}
		for (int i = 0; i < plantsmap.getBomb().size(); i++) {
			plantsmap.getBomb().get(i).setSuspend(false);
		}
	}

	public void passGame() {

		gamestate = "pass";
		backmusic2.Stop();
		passmusic.replay();
		for (Life l : plantsmap.zombies) {
			l.setLive(false);
		}
		for (Life l : plantsmap.plants) {
			l.setLive(false);
		}
		plantsmap.zombies.removeAll(PlantsMap.zombies);
		plantsmap.plants.removeAll(plantsmap.plants);
		pass.setLive(false);
		plantsmap.isLive = false;
		plantsbar.isLive = false;
		this.choosPass++;
	}

	/*
	 * 线程，实现面板的repaint() 并实现进入游戏时的动画
	 */
	class mainThread implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			while (true && !isGameOver) {

				/*
				 * 进入游戏是的动画
				 */
				if (gamestate == "gameover") {
					gameOver();
					return;
				}
				if (isPass) {
					passGame();
					return;
				}
				/*if (backgroudX > -500 && backflag) {
					backgroudX -= 1;
				} else {
					backflag = false;
					if (backgroudX < -150)
						backgroudX += 1;
					else {
						isPaintBegin = true;
						if (beginIndex != 0)
							beginIndex--;
						else {
							start = true;
							// 动画结束后启动游戏
							startAction();
						}
					}
				}*/
//				backgroudX = -150;
				start = true;
				// 动画结束后启动游戏
				startAction();

				try {
					Thread.sleep(5);
				} catch (InterruptedException e) {
					System.out.println("游戏运行出错");
					e.printStackTrace();
				}
				if (!gamestate.equals("pause") && !gamestate.equals("pass"))
					repaint();
			}
		}

	}

	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
	}

	public void paint(Graphics g) {
		super.paint(g);
		paintBack(g);
		if (isPaintBegin) {
			paintBegin(g);
		}
		if (start) {
			paintMenu(g);
			drawShadow(g);
			g.setFont(new Font("黑体", Font.BOLD, 30));
			g.setColor(Color.BLUE);
			g.drawString("第" + choosPass + "关", 750, 550);
			plantsbar.draw(g); // 画框
			plantsmap.drawPlant(g); // 画游戏场地
			plantsmap.drawSun(g); // 画阳光
			plantsmap.drawZombie(g); // 画僵尸
			plantsmap.drawBomb(g); // 画爆炸
			plantsmap.drawHead(g);
			plantsmap.drawSunCollection(g);
			drawMouseImg(g); // 画鼠标图案
		}
		if (gamestate.equals("gameover")) {
			g.drawImage(new ImageIcon("images/zombieWon.gif").getImage(), 0, 0, 900, 600, this);
		}
		if (gamestate.equals("pass")) {
			start = false;
			g.drawImage(ImageUtil.pattern2pass.getImage(), 0, 0, this);
		}
		if (isSelect) {
			paintSelectMenu(g);
		}

	}

	// 画游戏背景
	public void paintBack(Graphics g) {
		g.drawImage(backimage, backgroudX, 0, backimage.getWidth(null), backimage.getHeight(null), 0, 0,
				backimage.getWidth(null) - backgroudX, backimage.getHeight(null), null);// 画游戏背景
	}

	int menuflag = 0;

	public void paintMenu(Graphics g) {
		g.drawImage(ImageUtil.select[menuflag], 750, 0, null);
	}

	int selectflag = 1;

	public void paintSelectMenu(Graphics g) {
		g.drawImage(ImageUtil.selectmenu, 300, 100, null);
		g.drawImage(ImageUtil.fanhui[selectflag], 400, 250, 200, 50, null);
		g.drawImage(ImageUtil.fanhui[selectflag + 2], 400, 350, 200, 50, null);
	}

	// 画开始倒计时
	public void paintBegin(Graphics g) {
		if (beginIndex > 400) {
			if (beginIndex == 499)
				new MusicPlay(MusicUtil.READY).play();
			g.drawImage(ImageUtil.startready, 300, 300, this);
		} else if (beginIndex > 200) {
			g.drawImage(ImageUtil.startset, 300, 300, this);
		} else if (beginIndex > 0) {
			g.drawImage(ImageUtil.startplant, 300, 300, this);
		}
	}

	// 画鼠标图片
	private void drawMouseImg(Graphics g) {
		if (choosingPlant != PlantType.NONE) {
			Image img = choosingPlant.getPlantImg();
			g.drawImage(img, mouseX - Constant.CARD_WIDTH / 2, mouseY - Constant.CARD_HEIGHT / 2, null);
		}
	}

	// 画植物阴影
	public void drawShadow(Graphics g) {
		ImageUtil.setAlpha(g, 0.5f);
		g.drawImage(choosingPlant.getPlantImg(), shadowX, shadowY, null);
		ImageUtil.setAlpha(g, 1);
	}

	/**
	 * 键盘监听事件
	 * @author wangdongdong
	 *
	 */
	class myKeyListener extends KeyAdapter {
		@Override
		public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_P) {
				if (gamestate.equals("start")) {
					MainFrame.p1.pauseGame();
				} else if (gamestate.equals("pause")) {
					MainFrame.p1.continueGame();
				}
			}
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				if (gamestate.equals("pass")) {
					Init();
				} else if (gamestate.equals("gameover")) {
					isGameOver = true;
					// MainFrame.p1.pass.
					pass.setLive(false);
					MainFrame.p1.backmusic2.Stop();
					MainFrame.P.remove(MainFrame.p1);
					MainFrame.p1 = null;
					MainFrame.P.add(MainFrame.m);
					MainFrame.P.repaint();
					Menu.menu.loop();
					MainFrame.P.setVisible(true);
				}
			}
		}
	}


	@Override
	public void mouseMoved(MouseEvent e) {
		mouseX = e.getX();
		mouseY = e.getY();
		int col = (mouseX - MAP_WEST_OFFSET) / MAP_RECT_WIDTH; // 得到列
		int row = (mouseY - MAP_TOP_OFFSET) / MAP_RECT_HEIGHT; // 得到行
		if (col >= 0 && row >= 0 && col < MAP_COL && row < MAP_ROW) {
			shadowX = MAP_WEST_OFFSET + col * MAP_RECT_WIDTH;
			shadowY = MAP_TOP_OFFSET + row * MAP_RECT_HEIGHT;
		}
		if (mouseX > 200 && mouseX < 600 && mouseY > 0 && mouseY < 100) {
			MainFrame.P.setCursor(Cursor.HAND_CURSOR);
		} else
			MainFrame.P.setCursor(Cursor.DEFAULT_CURSOR);
		if (mouseX > 750 && mouseX < 863 && mouseY > 0 && mouseY < 40) {
			MainFrame.P.setCursor(Cursor.HAND_CURSOR);
			menuflag = 1;
		} else
			menuflag = 0;
		if (mouseX > 400 && mouseX < 600 && mouseY > 250 && mouseY < 300 && gamestate.equals("pause")) {
			MainFrame.P.setCursor(Cursor.HAND_CURSOR);
			selectflag = 0;
		} else
			selectflag = 1;
		if (mouseX > 400 && mouseX < 600 && mouseY > 350 && mouseY < 400 && gamestate.equals("pause")) {
			MainFrame.P.setCursor(Cursor.HAND_CURSOR);
			selectflag = 0;
		} else
			selectflag = 1;
		
		for (Sun sun : plantsmap.getSun()) {
			if (mouseX > sun.x && mouseX < sun.x + 100 && mouseY > sun.y && mouseY < sun.y + 100) {
				MainFrame.P.setCursor(Cursor.HAND_CURSOR);
			}
		}
		// 收集阳光
		plantsbar.collectSun(plantsmap.collectSun(mouseX, mouseY));
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		int x = e.getX();
		int y = e.getY();
		int col = (x - MAP_WEST_OFFSET) / MAP_RECT_WIDTH; // 得到列
		int row = (y - MAP_TOP_OFFSET) / MAP_RECT_HEIGHT; // 得到行
		if (e.getButton() == MouseEvent.BUTTON1 && gamestate == "start") {
			if (choosingPlant == PlantType.SHOVEL) {
				// 判断点击处是否有植物
				if (plantsmap.isPlant(row, col)) {
					plantsmap.removePlant(row, col);
					plantsbar.setShovelIsSelected(false);
					choosingPlant = PlantType.NONE;
				}
			}
			// 种植植物
			else if (choosingPlant != PlantType.NONE ) {
				if (plantsmap.inTheMap(x, y)) {
					if (plantsmap.putPlantInMap(choosingPlant, x, y))
						choosingPlant = PlantType.NONE;
				}

			}
			// 植物卡片选择
			else {
				choosingPlant = plantsbar.selectedPlant(new Point(x, y));
			}
		} else if (e.getButton() == MouseEvent.BUTTON3) {
			plantsbar.collectSun(choosingPlant.getCost(choosingPlant));
			if (plantsbar.isShovelIsSelected()) {
				plantsbar.setShovelIsSelected(false);
			}
			choosingPlant = PlantType.NONE;
		}
		
		if (x > 750 && x < 863 && y > 0 && y < 40) {
			isSelect = true;
			pauseGame();
			repaint();
		}
		if (mouseX > 400 && mouseX < 600 && mouseY > 250 && mouseY < 300) {
			if (gamestate.equals("pause")) {
				isSelect = false;
				continueGame();
			}
		}
		if (mouseX > 400 && mouseX < 600 && mouseY > 350 && mouseY < 400 && gamestate.equals("pause")) {

			isGameOver = true;
			// MainFrame.p1.pass.
			pass.setLive(false);
			MainFrame.p1.backmusic2.Stop();
			MainFrame.P.remove(MainFrame.p1);
			MainFrame.p1 = null;
			MainFrame.P.add(MainFrame.m);
			MainFrame.P.repaint();
			Menu.menu.loop();
			MainFrame.P.setVisible(true);
		}

	}

	@Override
	public void mouseDragged(MouseEvent e) {
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {}

	@Override
	public void mouseExited(MouseEvent e) {
	}
	
//	class backThread extends Thread {
//		@Override
//		public void run() {
//			while (true) {
//				if (isMove) {
//					if (backgroudX >-500 && backgroudX < 0) {
//						backgroudX += moveInstance;
//					}
//				}
//				try {
//					Thread.sleep(5);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}
	/*public backThread back_thread = new backThread();
	public boolean isMove = false;
	public int moveInstance = 1;*/
}
